import { resolve } from 'node:path'
import vue from '@vitejs/plugin-vue'
import dayjs from 'dayjs'
import pkg from './package.json'
import { loadEnv } from 'vite'
import autoprefixer from 'autoprefixer'
import { createHtmlPlugin } from 'vite-plugin-html'
import postCssPxToRem from 'postcss-pxtorem'

const CWD = process.cwd()

const getViteEnv = (mode, target) => {
 return loadEnv(mode, process.cwd())[target]
}

const __APP_INFO__ = {
 pkg,
 lastBuildTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
}

export default ({ command, mode }) => {
 const { VITE_BASE_URL, VITE_DROP_CONSOLE } = loadEnv(mode, CWD)
 return {
  base: VITE_BASE_URL,
  define: {
   __APP_INFO__: JSON.stringify(__APP_INFO__),
  },
  // 环境变量
  resolve: {
   alias: [
    {
     find: '@',
     replacement: resolve(__dirname, './src'),
    },
   ],
  },
  plugins: [
   createHtmlPlugin({
    inject: {
     data: {
      title: getViteEnv(mode, 'VITE_APP_TITLE'),
     },
    },
   }),
   vue(),
   autoprefixer({
    overrideBrowserslist: [
     'Android 4.1',
     'iOS 7.1',
     'Chrome > 31',
     'ff > 31',
     'ie >= 8',
    ],
   }),
  ],
  css: {
   postcss: {
    plugins: [
     postCssPxToRem({
      rootValue: 16, // 1rem的大小
      propList: ['*'], // 需要转换的属性，这里选择全部都进行转换
     })
    ]
   }
  },
  server: {
   host: '0.0.0.0',
   port: 9527,
   proxy:
    {},
  }
 }
}
